<template>
  <view class="page flex-col">
    <view class="text-wrapper_2 flex-col">
      <text class="text_3">认证车辆</text>
    </view>
    <text class="text_4">行车证</text>
    <view v-if="!vehicleImage" class="text-wrapper_3 flex-col" @click="chooseImage">
      <text class="text_5">请上传</text>
    </view>
    <image v-else class="license-preview" :src="vehicleImage" mode="aspectFill" @click="previewImage" />
    <view class="box_2 flex-col"></view>
    <view class="box_3 flex-row">
      <text class="text_6">车辆vin码</text>
	  <uni-tooltip class="tooltip" content="请输入车辆行驶证上的车辆识别代码">
	    <uni-icons type="help" size="18" color="#999"></uni-icons>
	  </uni-tooltip>
	  <view class="vin-input">
	    <input type="text" placeholder="请输入" v-model="vinCode" class="vin-input-field" />
	  </view>
    </view>
    <view class="box_4 flex-col"></view>
    <view class="box_5 flex-row justify-between">
      <text class="text_9" @click="cancelAction">取消</text>
      <view class="text-wrapper_5 flex-col" @click="addVehicle">
        <text class="text_10">添加车辆</text>
      </view>
    </view>
    <view class="box_6 flex-col">
      <view class="text-wrapper_7 flex-row">
        <text class="text_12">请输入车牌号</text>
      </view>
	  <car-number-input @numberInputResult="numberInputResult" :defaultStr="plateNumber"></car-number-input>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad as onPageLoad } from '@dcloudio/uni-app';
import { uploadFile } from '@/api/util.js';
import MyApi from '@/api/my/my.js';

// 响应式数据
const plateNumber = ref('');
const vinCode = ref('');
const isDef = ref(null);
const vehicleImage = ref('');
const relationId = ref(null);

// 读取路由参数（来自 bind.vue 跳转）
onPageLoad((options) => {
  try {
    relationId.value = options?.id ? Number(options.id) : null;
    if (relationId.value) {
      // 通过接口获取并预填车辆信息
      MyApi.getBoundVehicle(relationId.value)
        .then((data) => {
          try {
            // 按后端字段预填
            plateNumber.value = data?.plate || '';
            vinCode.value = data?.vin || '';
            vehicleImage.value = data?.vehicleLicenseFirst || '';
            isDef.value = data?.isDef || false;
          } catch (e) {
            console.warn('预填车辆信息解析失败:', e);
          }
        })
        .catch((err) => {
          console.warn('获取车辆信息失败:', err?.message || err);
        });
    } else if (options?.plate) {
      plateNumber.value = decodeURIComponent(options.plate);
    }
  } catch (e) {
    console.warn('解析路由参数失败:', e);
  }
});

// 车牌号输入结果处理
const numberInputResult = (result) => {
  plateNumber.value = result;
};

// 预览已上传图片
const previewImage = () => {
  if (!vehicleImage.value) return;
  uni.previewImage({ urls: [vehicleImage.value] });
};

// 选择并上传图片（参考 certification.vue 的实现）
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    extension: ['jpg', 'jpeg', 'png', 'webp', 'bmp'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];
      const fileSize = res.tempFiles?.[0]?.size ?? 0;

      const maxSize = 5 * 1024 * 1024;
      if (fileSize > maxSize) {
        uni.showToast({ title: '图片大小不能超过5MB', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '上传中...' });
      try {
        const pathParts = tempFilePath.split('/');
        const originalFileName = pathParts[pathParts.length - 1] || 'image.jpg';

        const result = await uploadFile(
          tempFilePath,
          'vehicle',
          originalFileName,
          'license',
          (progress) => {
            uni.showLoading({ title: `上传中...${progress}%` });
          },
          true,
          5
        );

        vehicleImage.value = result.url;
        uni.hideLoading();
        uni.showToast({ title: '上传成功', icon: 'success' });
      } catch (error) {
        console.error('上传失败:', error);
        uni.hideLoading();
        uni.showToast({ title: error.message || '上传失败，请重试', icon: 'none' });
      }
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
      uni.showToast({ title: '选择图片失败', icon: 'none' });
    }
  });
};

// 认证车辆：全部必填，调用 updateVehicle
const addVehicle = async () => {
  if (!plateNumber.value) {
    uni.showToast({ title: '请输入车牌号', icon: 'none' });
    return;
  }
  if (!vinCode.value) {
    uni.showToast({ title: '请输入车辆VIN码', icon: 'none' });
    return;
  }
  if (!vehicleImage.value) {
    uni.showToast({ title: '请上传行车证图片', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '提交中...' });
    if (!relationId.value) {
      uni.hideLoading();
      uni.showToast({ title: '缺少车辆关联ID', icon: 'none' });
      return;
    }
    const payload = {
      id: relationId.value,
      plate: plateNumber.value,
      vin: vinCode.value,
      isDef: isDef.value,
      vehicleLicenseFirst: vehicleImage.value
    };
    await MyApi.updateVehicle(payload);
    uni.hideLoading();
    uni.showToast({ title: '认证成功', icon: 'success' });
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
  } catch (e) {
    console.error('认证车辆失败:', e);
    uni.hideLoading();
    uni.showToast({ title: e?.message || '认证失败', icon: 'none' });
  }
};

// 取消操作
const cancelAction = () => {
  uni.showToast({
    title: '已取消操作',
    icon: 'none'
  });
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};
</script>

<style scoped>
.page {
  background-color: #ffffff;
  position: relative;
  width: 750rpx;
  height: 1620rpx;
  overflow: hidden;
  padding: 30rpx 0 60rpx 0;
}

.text-wrapper_2 {
  background-image: url(https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/vehicle/vehicle_background.png);
  margin-top: 60rpx;
  padding: 67rpx 473rpx 83rpx 46rpx;
}

.text_3 {
  overflow-wrap: break-word;
  color: #000000;
  font-size: 58rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 80rpx;
}

.text_4 {
  overflow-wrap: break-word;
  color: #7a7a7c;
  font-size: 27rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 38rpx;
  margin: 262rpx 630rpx 0 38rpx;
}

.text-wrapper_3 {
  border-radius: 4px;
  background-image: url(https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/images/vehicle/id_select.png);
  align-self: center;
  margin-top: 23rpx;
  width: 435rpx;
  padding: 163rpx 171rpx 38rpx 171rpx;
  background-repeat: no-repeat;
}

.license-preview {
  align-self: center;
  margin-top: 23rpx;
  width: 435rpx;
  height: 240rpx;
  border-radius: 4px;
}

.text_5 {
  overflow-wrap: break-word;
  color: #ffffff;
  font-size: 31rpx;
  font-weight: normal;
  text-align: center;
  white-space: nowrap;
  line-height: 42rpx;
}

.box_2 {
  background-color: #dcdfec;
  width: 712rpx;
  height: 2rpx;
  margin: 31rpx 0 0 38rpx;
}

.box_3 {
  width: 673rpx;
  align-self: center;
  margin-top: 31rpx;
}

.text_6 {
  overflow-wrap: break-word;
  color: #7a7a7c;
  font-size: 27rpx;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 38rpx;
  margin-top: 4rpx;
}

.tooltip {
  margin-left: 6rpx;
  margin-top: 4rpx;
}

.vin-input {
  flex: 1;
  text-align: right;
}

.vin-input-field {
  text-align: right;
  height: 42rpx;
  line-height: 42rpx;
  font-size: 31rpx;
  color: #333;
}

.box_4 {
  background-color: #dcdfec;
  width: 712rpx;
  height: 2rpx;
  margin: 31rpx 0 0 38rpx;
}

.box_5 {
  width: 654rpx;
  margin: 412rpx 38rpx 0 58rpx;
  position: fixed;
  bottom: 50rpx;
  left: 0;
}

.text_9 {
  overflow-wrap: break-word;
  color: #7a7a7c;
  font-size: 35rpx;
  font-weight: normal;
  text-align: right;
  white-space: nowrap;
  line-height: 48rpx;
  margin-top: 23rpx;
}

.text-wrapper_5 {
  background-color: #1ccbb4;
  border-radius: 25px;
  padding: 23rpx 181rpx 21rpx 181rpx;
}

.text_10 {
  overflow-wrap: break-word;
  color: #ffffff;
  font-size: 35rpx;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  text-align: right;
  white-space: nowrap;
  line-height: 48rpx;
}

.box_6 {
  background-color: #fff;
  border-radius: 10px;
  height: 252rpx;
  border: 1px solid #00D0B3;
  width: 680rpx;
  position: absolute;
  left: 30rpx;
  top: 295rpx;
  padding: 20rpx;
}

.text-wrapper_7 {
  margin: 20rpx;
}

.text_12 {
  overflow-wrap: break-word;
  color: #000000;
  font-size: 27rpx;
  font-family: MiSans-Regular;
  font-weight: normal;
  text-align: left;
  white-space: nowrap;
  line-height: 44rpx;
}

page view {
  box-sizing: border-box;
  flex-shrink: 0;
}

body {
  font-family: PingFangSC-Regular, Roboto, Helvetica Neue, Helvetica, Tahoma,
    Arial, PingFang SC-Light, Microsoft YaHei;
  margin: 0;
}

button {
  margin: 0;
  padding: 0;
  border: 1px solid transparent;
  outline: none;
  background-color: transparent;
}

button:active {
  opacity: 0.6;
}

.flex-col {
  display: flex;
  flex-direction: column;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.justify-start {
  display: flex;
  justify-content: flex-start;
}

.justify-center {
  display: flex;
  justify-content: center;
}

.justify-end {
  display: flex;
  justify-content: flex-end;
}

.justify-evenly {
  display: flex;
  justify-content: space-evenly;
}

.justify-around {
  display: flex;
  justify-content: space-around;
}

.justify-between {
  display: flex;
  justify-content: space-between;
}

.align-start {
  display: flex;
  align-items: flex-start;
}

.align-center {
  display: flex;
  align-items: center;
}

.align-end {
  display: flex;
  align-items: flex-end;
}
</style>
